package com.hunttown.mes.manage.controller._erp;

import com.hunttown.mes.common.OperateCode;
import com.hunttown.mes.manage.controller.common.AdminBaseClass;
import com.hunttown.mes.manage.controller.common.ModelService;
import com.hunttown.mes.rpc.domain.AnalysisManageDTO;
import com.hunttown.mes.rpc.domain.TransportCompanyDTO;
import com.hunttown.mes.rpc.domain.TransportPurchaseDTO;
import com.hunttown.mes.rpc.domain.TransportPurchaseDetailDTO;
import com.hunttown.mes.rpc.domain.enums.purchase.PurchaseDetailOutEnum;
import com.hunttown.mes.rpc.domain.enums.purchase.RPurchaseTypeEnum;
import com.hunttown.mes.rpc.domain.enums.pay.ReceiveWayEnum;
import com.hunttown.common.domain.Page;
import com.hunttown.mes.common.utils.*;
import com.hunttown.mes.manage.service.*;
import com.hunttown.mes.rpc.domain.query.TransportPurchaseDetailDTOQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

import static com.hunttown.mes.common.utils.PageUtils.PagePackage;

/**
 * @title: 采销详情
 * @author: wangjunfu
 * @date: 2019-05-25 10:36:38
 * @description:
 */
@Controller
@RequestMapping(value = "/erp/purchase-detail")
public class PurchaseDetailController {

    private final static Logger logger = LoggerFactory.getLogger(PurchaseDetailController.class);

    private final AnalysisManageManageService manageService;
    private final ModelService modelService;
    private final TransportCompanyManageService companyService;
    private final TransportOperateLogManageService logService;
    private final TransportPurchaseManageService purchaseService;
    private final TransportPurchaseDetailManageService purchaseDetailService;
    private final TransactionService transactionService;

    @Autowired
    public PurchaseDetailController(TransportPurchaseDetailManageService purchaseDetailService, AnalysisManageManageService manageService, TransportPurchaseManageService purchaseService, ModelService modelService, TransactionService transactionService, TransportOperateLogManageService logService, TransportCompanyManageService companyService) {
        this.purchaseDetailService = purchaseDetailService;
        this.manageService = manageService;
        this.purchaseService = purchaseService;
        this.modelService = modelService;
        this.transactionService = transactionService;
        this.logService = logService;
        this.companyService = companyService;
    }

    //region 数据列表

    /**
     * 首页
     *
     * @param model      model模型
     * @param partid     配件ID
     * @param optype     操作类型：1入库 2出库 3损坏
     * @param carId      车辆id
     * @param cUserName  物料领用人
     * @param sAdminName 物料损坏人
     * @return vm
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(HttpServletRequest request, Model model, Integer optype, Integer purchaseType, String likeName,
                        Integer partid, Integer carId,
                        Integer cUserId, String cUserName,
                        Integer sAdminId, String sAdminName, Integer pn) {

        if (optype < 0 || optype > 3) {
            throw new RuntimeException("未查询到配件信息");
        }

        if (pn == null || pn <= 0) {
            pn = 1;
        }

        //获取主配件信息（新版改名为现货入库，不需要此判断）
        //TransportPurchaseDTO obj = purchaseService.getById(partid);
        //if (obj == null) {
        //    throw new RuntimeException("未查询到配件信息");
        //}
        //model.addAttribute("partObj", obj);

        //新版现货入库条件：table_id=50；record_id=0；pro_id=0；pur_id=0；op_type=1；r_purchase_type=1
        TransportPurchaseDetailDTOQuery query = new TransportPurchaseDetailDTOQuery();
        query.setPn(pn);
        query.setPartId(partid);
        query.setOpType(optype);

        //新版增加
        query.setTableId(50);
        query.setRecordId(0);
        query.setPurId(0);
        query.setProId(0);
        query.setPurchaseType(purchaseType);
        query.setrPurchaseType(1);

        //模糊查询
        if (StringUtils.isNotBlank(likeName)) {
            List<Integer> partIds = purchaseService.getIdListByPartName(likeName);
            partIds.add(-1); //如果没查询到配件，这样也不会乱显示
            query.setPartIds(partIds);
        }

        if (carId != null && carId > 0) {
            query.setcCarId(carId);
        }
        if (cUserId != null && cUserId > 0) {
            query.setcUserId(cUserId);
        }
        if (sAdminId != null && sAdminId > 0) {
            query.setsAdminId(sAdminId);
        }

        query.setStopFlag(0);
        query.setOrderBy("order by id desc");
        Page<TransportPurchaseDetailDTO> dataPage = purchaseDetailService.getForPage(query);

        // 实时更新列表信息
        if (dataPage != null && dataPage.getItems().size() > 0) {
            for (TransportPurchaseDetailDTO item : dataPage.getItems()) {
                if (optype == 1) {  //入库
                    item.setrPurchaserName(modelService.getManageName(item.getrPurchaser()));
                    item.setPartName(modelService.getPurchaseName(item.getPartId()));
                }

                if (optype == 2) {  //出库
                    item.setcUserName(modelService.getUserTrueName(item.getcUserId()));

                    //出库形式
                    item.setcOutTypeName(PurchaseDetailOutEnum.getEnumByKey(item.getcOutType()));
                }

                if (optype == 3) {  //损坏
                    item.setsAdminName(modelService.getUserTrueName(item.getsAdminId()));
                    item.setReviewerCn(modelService.getUserTrueName(item.getReviewer()));
                }
            }
        }

        model.addAttribute("page", dataPage);
        model.addAttribute("PagePackage", PagePackage(dataPage.getPn(), dataPage.getStart(), dataPage.getPageSize(), dataPage.getTotalPages(), dataPage.getTotalItems()));

        model.addAttribute("likeName", likeName);
        model.addAttribute("carId", carId);
        model.addAttribute("cUserId", cUserId);
        model.addAttribute("cAdminName", cUserName);
        model.addAttribute("sAdminId", sAdminId);
        model.addAttribute("sAdminName", sAdminName);

        //判断当前操作类型
        if (optype == 1) {
            //model.addAttribute("showTitle", "入库明细");
            model.addAttribute("showTitle", "现货入库");
        } else if (optype == 2) {
            model.addAttribute("showTitle", "出库明细");

        } else if (optype == 3) {
            model.addAttribute("showTitle", "部损明细");
        } else {
            model.addAttribute("showTitle", "非法请求");
        }
        model.addAttribute("optype", optype);
        model.addAttribute("purchaseType", purchaseType);

        //region 页面按钮权限
        String pin = AdminBaseClass.getPin(request);
        String[] menus = {"X-W-WLGL-MXBJ", "X-W-WLGL-MXSC", "Q-P-PJXX-MXBJ", "Q-P-PJXX-MXSC"};
        model.addAttribute("Permission", manageService.GetBtnPermission(menus, pin));
        //endregion

        return "erp/purchase-detail/index";
    }

    /**
     * 详情
     *
     * @param model model
     * @param id    明细Id
     * @return vm
     */
    @RequestMapping(value = "/detail", method = RequestMethod.GET)
    public String detail(Model model, Integer id) {
        if (id == null || id <= 0) {
            throw new RuntimeException("未找到配件信息！");
        }

        TransportPurchaseDetailDTO obj = purchaseDetailService.getById(id);
        if (obj != null) {

            obj.setReviewerCn(modelService.getUserTrueName(obj.getReviewer()));

            //供应商
            obj.setrCompanyName(modelService.getCompanyName(obj.getrCompanyId()));

            //采购人
            obj.setrPurchaserName(modelService.getManageName(obj.getrPurchaser()));

            //付款单位
            obj.setrPayCompanyName(modelService.getCompanyName(obj.getrPayCompanyId()));

            //付款方式
            obj.setrPayWayName(ReceiveWayEnum.getEnumByKey(obj.getrPayWay()));

            //入库形式
            obj.setrPurchaseTypeName(RPurchaseTypeEnum.getEnumByKey(obj.getrPurchaseType()));

            //获取主配件信息
            TransportPurchaseDTO partObj = purchaseService.getById(obj.getPartId());
            if (partObj == null) {
                throw new RuntimeException("未查询到配件信息");
            }

            //适用车型
            partObj.setModelCn(modelService.getCatalogName(partObj.getModelId()));

            //类别名称
            partObj.setCatalogName(modelService.getCatalogName(partObj.getCatalogId()));

            //仓库
            partObj.setStorageName(modelService.getCatalogName(partObj.getStorage()));

            model.addAttribute("partObj", partObj);
        }

        model.addAttribute("Obj", obj);

        return "erp/purchase-detail/detail";
    }

    //出库查询
    @RequestMapping(value = "/searchOutIndex", method = RequestMethod.GET)
    public String searchOutIndex(Model model, TransportPurchaseDetailDTOQuery dtoQuery) {
        int optype = 2;  //操作类型：1入库 2出库 3损坏

        //配件模糊搜索
        if (StringUtils.isNotBlank(dtoQuery.getLikeName())) {
            List<Integer> partIds = purchaseService.getIdListByPartName(dtoQuery.getLikeName());
            partIds.add(-1);
            dtoQuery.setPartIds(partIds);
        }

        dtoQuery.setcUserId(modelService.completionUserId(dtoQuery.getcUserId(), dtoQuery.getcUserName(), -9999));
        dtoQuery.setOpType(optype);
        dtoQuery.setStopFlag(0);
        dtoQuery.setOrderBy("order by c_out_date desc, id desc");
        Page<TransportPurchaseDetailDTO> dataPage = purchaseDetailService.getForPage(dtoQuery);

        // 实时更新列表信息
        if (dataPage != null && dataPage.getItems().size() > 0) {
            for (TransportPurchaseDetailDTO item : dataPage.getItems()) {
                item.setPartName(modelService.getPurchaseName(item.getPartId()));
                item.setcUserName(modelService.getUserTrueName(item.getcUserId()));

                //出库形式
                item.setcOutTypeName(PurchaseDetailOutEnum.getEnumByKey(item.getcOutType()));
            }
        }

        model.addAttribute("page", dataPage);
        model.addAttribute("PagePackage", PagePackage(dataPage.getPn(), dataPage.getStart(), dataPage.getPageSize(), dataPage.getTotalPages(), dataPage.getTotalItems()));
        model.addAttribute("dtoQuery", dtoQuery);
        model.addAttribute("optype", optype);

        return "erp/purchase-detail/index_out";
    }

    //出入库查询（全部）
    @RequestMapping(value = "/inOutRecord", method = RequestMethod.GET)
    public String inOutRecord(Model model, TransportPurchaseDetailDTOQuery dtoQuery) {

        //获取主配件信息（新版改名为现货入库，不需要此判断）
        TransportPurchaseDTO obj = purchaseService.getById(dtoQuery.getPartId());
        if (obj == null) {
            throw new RuntimeException("未查询到配件信息");
        }
        model.addAttribute("partObj", obj);

        dtoQuery.setOrderBy("order by id desc");
        Page<TransportPurchaseDetailDTO> dataPage = purchaseDetailService.getForPage(dtoQuery);

        // 实时更新列表信息
        if (dataPage != null && dataPage.getItems().size() > 0) {
            for (TransportPurchaseDetailDTO item : dataPage.getItems()) {
                if (item.getOpType() == 1) {  //入库
                    item.setrPurchaserName(modelService.getManageName(item.getrPurchaser()));
                }

                if (item.getOpType() == 2) {  //出库
                    item.setcUserName(modelService.getUserTrueName(item.getcUserId()));

                    //出库形式
                    item.setcOutTypeName(PurchaseDetailOutEnum.getEnumByKey(item.getcOutType()));
                }

                if (item.getOpType() == 3) {  //损坏
                    item.setsAdminName(modelService.getUserTrueName(item.getsAdminId()));
                    item.setReviewerCn(modelService.getUserTrueName(item.getReviewer()));
                }
            }
        }

        model.addAttribute("page", dataPage);
        model.addAttribute("PagePackage", PagePackage(dataPage.getPn(), dataPage.getStart(), dataPage.getPageSize(), dataPage.getTotalPages(), dataPage.getTotalItems()));
        model.addAttribute("purchaseType", dtoQuery.getPurchaseType());

        return "erp/purchase-detail/index_in_out";
    }
    //endregion

    //region 编辑&保存（新版改为采购单、出库单，此方法改为现货入库）

    /**
     * 编辑
     *
     * @param model         model模型
     * @param id            主键id
     * @param partid        配件ID
     * @param optype        操作类型：1入库 2出库 3损坏
     * @param rpurchasetype 入库形式：1采购 2提报
     * @param isIncome      1入库
     * @param cnoorder      1无单出库 0维修出库
     * @return vm
     */
    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String edit(Model model, Integer id, Integer partid, Integer optype, Integer purchaseType,
                       Integer rpurchasetype, Integer isIncome, Integer cnoorder) {

        id = (id == null ? 0 : id);
        cnoorder = (cnoorder == null ? 0 : cnoorder);

        if (optype < 0 || optype > 3) {
            throw new RuntimeException("未查询到配件信息");
        }

        //获取主配件信息（新版改名为现货入库，不需要此判断）
        //TransportPurchaseDTO partObj = purchaseService.getById(partid);
        //if (partObj == null) {
        //    throw new RuntimeException("未查询到配件信息");
        //}
        //model.addAttribute("partObj", partObj);

        //默认 采购
        if (rpurchasetype == null || rpurchasetype <= 0) {
            rpurchasetype = 1;
        }

        //获取当前记录信息
        TransportPurchaseDetailDTO obj;

        if (id > 0) {
            obj = purchaseDetailService.getById(id);

            //入库（提报）
            if (obj.getOpType() == 1 && obj.getrPurchaseType() == 2) {
                obj.setReviewerCn(modelService.getUserTrueName(obj.getReviewer()));

                if (isIncome != null && isIncome == 1) {
                    obj.setId(0);
                    obj.setrPurchaseType(1);
                    obj.setRelationId(id);
                }
            }

            //出库
            if (obj.getOpType() == 2) {
                obj.setcUserName(modelService.getUserTrueName(obj.getcUserId()));
                obj.setReviewerCn(modelService.getUserTrueName(obj.getReviewer()));
            }

            //损坏
            if (obj.getOpType() == 3) {
                obj.setsAdminName(modelService.getUserTrueName(obj.getsAdminId()));
                obj.setReviewerCn(modelService.getUserTrueName(obj.getReviewer()));
            }

        } else {
            obj = new TransportPurchaseDetailDTO();
            obj.setId(id);

            //默认值
            String dt = DateConvertUtils.dateToShortStr(new Date());
            BigDecimal zero = BigDecimal.ZERO;
            obj.setPurchaseType(purchaseType);
            obj.setrPurchaseType(rpurchasetype);
            obj.setrStoreCount(0);
            obj.setrPrice(zero);
            obj.setrCount(optype == 1 ? 1 : 0);
            obj.setrAmount(zero);
            obj.setrPurchaseDateSr(dt);
            obj.setrInDateSr(dt);
            obj.setrSalePrice(BigDecimal.ZERO);
            obj.setrMarketPrice(zero);
            obj.setrStorePrice(zero);
            obj.setrTaxRate(zero);
            obj.setrTax(zero);
            obj.setrPayWay(1);
            obj.setcNoOrder(cnoorder);
            obj.setcUserId(0);
            obj.setcStoreCount(0);
            obj.setcCount(optype == 2 ? 1 : 0);
            obj.setcCountAll(0);
            obj.setcCountReal(0);
            obj.setcCountReturn(0);
            obj.setcCountNouse(0);
            obj.setcOutDateSr(dt);
            obj.setcCarId(0);
            obj.setcDriverId(0);
            obj.setsCount(optype == 3 ? 1 : 0);
            obj.setsAdminId(0);
            obj.setsDateSr(dt);
            obj.setReviewer(0);
            obj.setBxId(0);
            obj.setRelationId(0);
            obj.setApplyId(0);

            //出库方式：1消耗 2借用 3退货
            if (optype == 1) {
                obj.setcOutType(0);
            } else {
                obj.setcOutType(1);
            }
        }

        model.addAttribute("Obj", obj);

        //判断当前操作类型
        if (optype == 1) {
            //model.addAttribute("showTitle", "入库明细");
            model.addAttribute("showTitle", "现货入库");

            //获取采购人
            modelService.getManagerPage(model);

            //供应商
            modelService.getCompayPage(model, 2);

            //付款单位
            modelService.getCompayPage(model, 7, null, "receivePayList");

            //付款方式
            model.addAttribute("receiveWayList", ReceiveWayEnum.getEnumList());

            //入库形式
            model.addAttribute("rPurchaseTypeList", RPurchaseTypeEnum.getEnumList());

        } else if (optype == 2) {
            model.addAttribute("showTitle", "出库明细");

            //出库方式
            model.addAttribute("purchaseOutList", PurchaseDetailOutEnum.getEnumList("1,2,3,4"));

        } else if (optype == 3) {
            model.addAttribute("showTitle", "部损明细");

        } else {
            model.addAttribute("showTitle", "非法请求");
        }
        model.addAttribute("optype", optype);

        return "erp/purchase-detail/edit";
    }

    /**
     * 保存 ajax异步
     * 此方法重点说明一下，新版改版以后，采购、出入库都开发了单独的功能
     * 此方法修改为现货入库（不需要审批）所以此方法中大部分功能都没有，只有入库这一个环节有用
     * 其它功能暂时保留，不做删减
     *
     * @param request sevelet请求
     * @param objDTO  实体类
     * @return json
     */
    @RequestMapping(value = "/saveEdit", method = RequestMethod.POST)
    @ResponseBody
    public String saveEditNotify(HttpServletRequest request, TransportPurchaseDetailDTO objDTO) {

        // 结果返回 结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        try {
            objDTO.setcRepairId(0);

            //region //合法性条件判断

            //配件、采购入库，必须填写采购人
            if (objDTO.getOpType() == 1) {
                if (objDTO.getPartId() <= 0) {
                    map = OperateCode.CompositionResult(map, -10, "请选择入库物料！");
                    result = JSONUtils.toJSON(map);
                    return result;
                }

                if (objDTO.getrPurchaser() == 0) {
                    map = OperateCode.CompositionResult(map, -10, "请选择采购人！");
                    result = JSONUtils.toJSON(map);
                    return result;
                }

                if (objDTO.getrCount() <= 0) {
                    map = OperateCode.CompositionResult(map, -10, "请填写采购数量！");
                    result = JSONUtils.toJSON(map);
                    return result;
                }

                //初始值
                objDTO.setrInCount(objDTO.getrCount());

            } else {
                //非入库时，给初始值
                objDTO.setrPurchaseType(0);
                objDTO.setrCompanyId(0);
                objDTO.setrTaxRate(new BigDecimal(0));
                objDTO.setrTax(new BigDecimal(0));
                objDTO.setrPayCompanyId(0);
                objDTO.setrPayWay(0);
            }

            //入库>提报，必须写复核人
            if (objDTO.getOpType() == 1 && objDTO.getrPurchaseType() == 2) {
                if (objDTO.getReviewer() == 0) {
                    map = OperateCode.CompositionResult(map, -10, "请填写复核人！");
                    result = JSONUtils.toJSON(map);
                    return result;
                }
            }

            //配件>（有单）出库>消耗，检验维修单号
            if (objDTO.getOpType() == 2 && objDTO.getcNoOrder() == 0 && objDTO.getPurchaseType() == 1 && objDTO.getcOutType() == 1) {
                if (StringUtils.isBlank(objDTO.getRepairNo())) {
                    map = OperateCode.CompositionResult(map, -10, "请输入维修单号！");
                    result = JSONUtils.toJSON(map);
                    return result;
                }

                objDTO.setReviewer(0);
            }

            //配件（无单）出库必须填写司机和车辆
            if (objDTO.getcNoOrder() == 1 && objDTO.getcOutType() == 1) {
                if (objDTO.getcCarId() == 0 || objDTO.getcDriverId() == 0) {
                    map = OperateCode.CompositionResult(map, -10, "配件无单出库必须填写司机和车辆！");
                    result = JSONUtils.toJSON(map);
                    return result;
                }
            }

            //出库
            if (objDTO.getOpType() == 2) {
                if (objDTO.getcOutType() > 1) { //1消耗 2借用 3退货
                    if (objDTO.getcUserId() == 0) {
                        map = OperateCode.CompositionResult(map, -10, "请填写使用人！");
                        result = JSONUtils.toJSON(map);
                        return result;
                    }

                    if (objDTO.getReviewer() == 0) {
                        map = OperateCode.CompositionResult(map, -10, "请填写复核人！");
                        result = JSONUtils.toJSON(map);
                        return result;
                    }
                }

                if (objDTO.getcCount() <= 0) {
                    map = OperateCode.CompositionResult(map, -10, "请填写出库数量！");
                    result = JSONUtils.toJSON(map);
                    return result;
                }
            }

            //物料损坏
            if (objDTO.getOpType() == 3) {
                if (objDTO.getsAdminId() == 0) {
                    map = OperateCode.CompositionResult(map, -10, "请填写损坏人！");
                    result = JSONUtils.toJSON(map);
                    return result;
                }

                if (objDTO.getReviewer() == 0) {
                    map = OperateCode.CompositionResult(map, -10, "请填写复核人！");
                    result = JSONUtils.toJSON(map);
                    return result;
                }

                if (objDTO.getsCount() <= 0) {
                    map = OperateCode.CompositionResult(map, -10, "请填写损坏数量！");
                    result = JSONUtils.toJSON(map);
                    return result;
                }
            }

            //endregion

            //日期转化
            objDTO.setrPurchaseDate(DateConvertUtils.strToDate(objDTO.getrPurchaseDateSr()));
            objDTO.setrInDate(DateConvertUtils.strToDate(objDTO.getrInDateSr()));
            objDTO.setcOutDate(DateConvertUtils.strToDate(objDTO.getcOutDateSr()));
            objDTO.setsDate(DateConvertUtils.strToDate(objDTO.getsDateSr()));

            //获取配件名称
            TransportPurchaseDTO partDTO = purchaseService.getById(objDTO.getPartId());

            String pin = AdminBaseClass.getPin(request);
            AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);

            if (objDTO.getId() == null || objDTO.getId() <= 0) {

                //region STEP 01 伪事务 - 新增
                objDTO.setAdminId(curr_obj.getId());
                objDTO.setCreateTime(new Date());
                objDTO.setDeleteFlag(0);

                //生成出入库单号
                String suffix = GeneralUtils.autoGenericCode(objDTO.getOpType(), 2);
                objDTO.setPurchasetNo(GeneralUtils.GenTimeSeries(2, "PJ", suffix));
                objDTO.setStatus(0);
                objDTO.setBxId(0);
                objDTO.setApplyId(0);
                objDTO.setParentId(0);
                objDTO.setTableId(50);
                objDTO.setRecordId(0);
                objDTO.setProId(0);
                objDTO.setPurId(0);

                //获取一下主表的 purchaseType
                TransportPurchaseDTO purchaseDTO = purchaseService.getById(objDTO.getPartId());
                objDTO.setPurchaseType(purchaseDTO.getPurchaseType());

                objDTO.setReviewDate(DateConvertUtils.strToDate("1990-01-01"));
                objDTO.setReviewStatus(0);

                objDTO = purchaseDetailService.insert(objDTO);

                if (objDTO == null || objDTO.getId() <= 0) {
                    //操作失败
                    map = OperateCode.CompositionResult(map, -1);
                    result = JSONUtils.toJSON(map);
                    return result;
                }

                //入库成功以后，将提报单状态改成已入库
                if (objDTO.getRelationId() != null && objDTO.getRelationId() > 0) {
                    TransportPurchaseDetailDTO incomeDto = new TransportPurchaseDetailDTO();
                    incomeDto.setId(objDTO.getRelationId());
                    incomeDto.setStatus(10);
                    purchaseDetailService.updateInfoById(incomeDto);
                }

                //endregion

                //region STEP 02 - 事务 - 生成审批流程

                // 配件和日常采购（损坏 || 配件，非消耗出库 || 日常采购，出库 || 入库，提报）
                // opType：1入库 2出库 3损坏
                if (objDTO.getOpType() == 3 || objDTO.getcNoOrder() == 1 ||
                        (objDTO.getOpType() == 2 && objDTO.getPurchaseType() == 1 && objDTO.getcOutType() > 1) ||
                        (objDTO.getOpType() == 2 && objDTO.getPurchaseType() == 2) ||
                        (objDTO.getOpType() == 1 && objDTO.getrPurchaseType() == 2)) {

                    // 以下六种情况
                    //1.物料损坏
                    //2.出库（日常采购：物料领取）
                    //3.出库（借用）
                    //4.出库（退货）
                    //5.出库（配件无单出库）
                    //6.入库（提报）

                    String businessName = null;
                    Map<String, String> param = new HashMap<>();

                    //第一审批人
                    Integer firstUserId = 0;
                    //第二审批人
                    Integer secondUserId = 0;

                    //region [1].入库
                    if (objDTO.getOpType() == 1) {
                        //日常采购、配件：提报
                        if (objDTO.getrPurchaseType() == 2) {
                            businessName = "purchase_ready";
                            param.put("applyTitle", String.format("%s（%s）提报", modelService.getManageName(objDTO.getrPurchaser()), partDTO.getPartName())); //管理员ID
                            firstUserId = modelService.getUserIdByAdminId(objDTO.getrPurchaser());
                            secondUserId = objDTO.getReviewer();
                        }
                    }
                    //endregion

                    //region [2].出库
                    if (objDTO.getOpType() == 2) {

                        firstUserId = objDTO.getcUserId();
                        secondUserId = objDTO.getReviewer();

                        //region 配件
                        if (objDTO.getPurchaseType() == 1) {

                            //配件：无单出库
                            if (objDTO.getcOutType() == 1 && objDTO.getcNoOrder() == 1) {
                                businessName = "parts_outbound";
                                param.put("applyTitle", String.format("%s（%s）无单出库", "司机", partDTO.getPartName()));
                                firstUserId = modelService.getUserIdByAdminId(curr_obj.getId());
                                secondUserId = modelService.getUserIdByDriverId(objDTO.getcDriverId());
                            }

                            //配件：借用
                            if (objDTO.getcOutType() == 2) {
                                businessName = "parts_borrow";
                                param.put("applyTitle", String.format("%s（%s）借用", modelService.getUserTrueName(objDTO.getcUserId()), partDTO.getPartName()));
                            }

                            //配件：退货
                            if (objDTO.getcOutType() == 3) {
                                businessName = "parts_return";
                                param.put("applyTitle", String.format("%s（%s）退货", modelService.getUserTrueName(objDTO.getcUserId()), partDTO.getPartName()));
                            }
                        }
                        //endregion

                        //region 日常采购
                        if (objDTO.getPurchaseType() == 2) { //采购

                            //日常采购：领取
                            if (objDTO.getcOutType() == 1) {
                                businessName = "goods_receiving";
                                param.put("applyTitle", String.format("%s（%s）领取", modelService.getUserTrueName(objDTO.getcUserId()), partDTO.getPartName()));
                            }

                            //日常采购：借用
                            if (objDTO.getcOutType() == 2) {
                                businessName = "goods_borrow";
                                param.put("applyTitle", String.format("%s（%s）借用", modelService.getUserTrueName(objDTO.getcUserId()), partDTO.getPartName()));
                            }

                            //日常采购：退货
                            if (objDTO.getcOutType() == 3) {
                                businessName = "goods_return";
                                param.put("applyTitle", String.format("%s（%s）退货", modelService.getUserTrueName(objDTO.getcUserId()), partDTO.getPartName()));
                            }
                        }
                        //endregion
                    }
                    //endregion

                    //region [3].损坏
                    if (objDTO.getOpType() == 3) {
                        //物料损坏
                        businessName = "goods_damage";
                        param.put("applyTitle", String.format("%s（%s）损坏", modelService.getUserTrueName(objDTO.getsAdminId()), partDTO.getPartName())); //会员ID
                        firstUserId = objDTO.getsAdminId();
                        secondUserId = objDTO.getReviewer();
                    }
                    //endregion

                    //[改版后]审批人走的是会员系统
                    param.put("firstExector", firstUserId + "");
                    param.put("secondExector", secondUserId + "");

                    Integer applyId = transactionService.createApplyWithout(businessName, "transport_purchase_detail", objDTO.getId(), objDTO.getAdminId(), param);
                    if (applyId > 0) {

                        //更新出库表中的applyId
                        TransportPurchaseDetailDTO updateDto = new TransportPurchaseDetailDTO();
                        updateDto.setId(objDTO.getId());
                        updateDto.setApplyId(applyId);
                        purchaseDetailService.updateInfoById(updateDto);

                    } else {

                        // 审批流程生成失败 删除已经生成的出库单
                        TransportPurchaseDetailDTO updateDto = new TransportPurchaseDetailDTO();
                        updateDto.setId(objDTO.getId());
                        updateDto.setStopFlag(1);
                        purchaseDetailService.updateInfoById(updateDto);

                        //程序终止，返回失败信息
                        map = OperateCode.CompositionResult(map, -1);
                        result = JSONUtils.toJSON(map);
                        return result;
                    }

                }

                //endregion

            } else {
                //更新
                //将不需要更新的字段设置为NULL
                objDTO.setPurchasetNo(null);

                Boolean isNext = purchaseDetailService.updateInfoById(objDTO);
                if (isNext) {

                    //region //设置第1审批人和每2审批人
                    if (objDTO.getApplyId() != null && objDTO.getApplyId() > 0) {

                        //物料采购出库
                        if (objDTO.getOpType() == 2 && objDTO.getPurchaseType() == 2) { //采购
                            Integer firstExector = objDTO.getcUserId();
                            Integer secondExector = objDTO.getReviewer();

                            Map<Integer, Integer> replaceMap = new HashMap<>();
                            replaceMap.put(1, firstExector);
                            replaceMap.put(2, secondExector);
                            transactionService.setExector(objDTO.getApplyId(), replaceMap);
                        }

                        //配件/物料损坏
                        if (objDTO.getOpType() == 3) {
                            Integer firstExector = objDTO.getsAdminId();
                            Integer secondExector = objDTO.getReviewer();

                            Map<Integer, Integer> replaceMap = new HashMap<>();
                            replaceMap.put(1, firstExector);
                            replaceMap.put(2, secondExector);
                            transactionService.setExector(objDTO.getApplyId(), replaceMap);
                        }
                    }
                    //endregion

                } else {
                    //操作失败
                    map = OperateCode.CompositionResult(map, -1);
                    result = JSONUtils.toJSON(map);
                    return result;
                }
            }

            //region *** 更新信息完毕记录操作日志 ***
            logService.insertSimple(1, 51, objDTO.getId(), 2,
                    "更新配件、采购明细信息",
                    FastJsonUtils.toJSONString(objDTO),
                    curr_obj.getId(),
                    IpUtils.getClientIp(request),
                    SystemUtils.getBrowserInfo(request));
            //endregion

            //操作成功 结果返回
            map = OperateCode.CompositionResult(map, 1);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }

    }
    //endregion

    //region 删除

    /**
     * 通过id删除 ajax异步
     *
     * @param id 记录id
     * @return json
     */
    @RequestMapping(value = "/deleteById", method = RequestMethod.POST)
    @ResponseBody
    public String deleteNotify(HttpServletRequest request, Integer id) {

        // 结果返回结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        if (id == null || id <= 0) {
            map = OperateCode.CompositionResult(map, -10, "请选择要删除的记录！");
            result = JSONUtils.toJSON(map);
            return result;
        }

        try {
            Boolean isNext = purchaseDetailService.delete(id);

            //region *** 更新信息完毕记录操作日志 ***
            String pin = AdminBaseClass.getPin(request);
            AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);
            logService.insertSimple(1, 51, id, 4,
                    "删除配件、采购明细信息",
                    "记录删除：" + (isNext ? "成功" : "失败") + "：" + id,
                    curr_obj.getId(),
                    IpUtils.getClientIp(request),
                    SystemUtils.getBrowserInfo(request));
            //endregion

            map = OperateCode.CompositionResult(map, isNext ? 1 : 0);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }

    //endregion

}